package com.derbysoft.ota.application.util;

import java.util.Calendar;

import org.apache.commons.beanutils.BeanUtils;

import com.googlecode.functionalcollections.FunctionalIterable;
import com.googlecode.functionalcollections.FunctionalIterables;


public abstract class PayloadStdAttributes {

	public static <T> T copy(Object rq, T rs) {
		Beans.copyProperties(rq, rs, fieldNames());
		try {
			BeanUtils.setProperty(rs, "timeStamp", Calendar.getInstance(Calendars.gmt0TimeZone()));
		} catch (Exception e) {
			throw new RuntimeException("No writable timeStamp field of : " + rs, e);
		}
		try {
			Object retransmissionIndicator = retransmissionIndicator(rq);
			if (retransmissionIndicator != null) {
				BeanUtils.setProperty(rs, "retransmissionIndicator", retransmissionIndicator);
			}
		} catch (Exception e) {
			throw new RuntimeException("Couldn't read retransmissionIndicator field of : " + rq, e);
		}
		return rs;
	}

	private static Object retransmissionIndicator(Object rq) throws Exception {
		// JAXB don't generate a stand getter method for retransmissionIndicator
		return rq.getClass().getMethod("isRetransmissionIndicator", new Class[] {}).invoke(rq, new Object[] {});
	}

	private static FunctionalIterable<String> fieldNames() {
		return FunctionalIterables.<String>create()
								.concat("echoToken")
								.concat("target")
								.concat("version")
								.concat("transactionIdentifier")
								.concat("sequenceNmbr")
								.concat("transactionStatusCode")
								.concat("correlationID")
								.concat("primaryLangID")
								.concat("altLangID");
	}

}
